<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>之易数据同步</title>
</head>
<script src="/webjars/jquery/3.0.0/jquery.min.js"></script>
<script src="/webjars/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="/js/jquery.cookie.min.js"></script>
<link href="/webjars/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script>
  var socket;

  /**
   * jquery的初始化
   **/
  $(document).ready(function () {

    //初始化使用说明文档
    initReadme();
    //初始化
    connected();
    //初始化平台信息
    initPlatformInfo();
  });

  /**
   * 初始化阅读文档
   */
  function initReadme() {
    $("#divLeftTopTextarea").append("【之易DB】\n");
    $("#divLeftTopTextarea").append("1. 请确保执行的sql是正确的\n");
    $("#divLeftTopTextarea").append("2. 执行多个SQL请以英文逗号隔开\n");
    $("#divLeftTopTextarea").append("3. 请确定好执行执行是否需要备份\n");
    /*$("#divLeftTopTextarea").scrollTop($("#divLeftTopTextarea")[0].scrollHeight);*/
  }

  /**
   *建立连接
   *
   **/
  function openSocket(clientCode) {
    if (typeof (WebSocket) == "undefined") {
      alert("您的浏览器不支持WebSocket");
    } else {
      //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
      //等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
      let baseSocketUrl = $("#socketUrlId").val();
      var socketUrl = baseSocketUrl + "/zydb/" + clientCode;
      socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
      if (socket != null) {
        socket.close();
        socket = null;
      }

      socket = new WebSocket(socketUrl);
      $("#onlineimg").attr("src", '/images/online/online.png');
      $("#onlinespan").text("在线[" + clientCode + "]");

      //打开事件[websocket已打开][socket.send("这是来自客户端的消息" + location.href + new Date());]
      socket.onopen = function () {

      };
      //获得消息事件
      socket.onmessage = function (msg) {
        let data = JSON.parse(msg.data);
        var idinfo = "";
        if (data.type == 2) {
          idinfo = "#divCenterTextarea";
        } else if (data.type == 3) {
          idinfo = "#divRightTextarea";
        } else {
          idinfo = "#divLeftTextarea";
        }
        if (idinfo) {
          $(idinfo).append(data.msg + "\n");
          $(idinfo).scrollTop($(idinfo)[0].scrollHeight);
        }
      };
      //关闭事件
      socket.onclose = function () {
        alert("连接长时间未使用断开连接,请点击\"点击启动\"进行重连在操作其他的");
        console.log("websocket已关闭");
      };
      //发生了错误事件
      socket.onerror = function () {
        console.log("websocket发生了错误");
      }
    }
  }

  /**
   * 发送消息
   */
  function sendMessage() {
    if (typeof (WebSocket) == "undefined") {
      alert("您的浏览器不支持WebSocket");
    } else {
      console.log('{"toUserId":"' + $("#toUserId").val() + '","contentText":"' + $("#contentText").val() + '"}');
      socket.send('{"toUserId":"' + $("#toUserId").val() + '","contentText":"' + $("#contentText").val() + '"}');
    }
  }

  /**
   * 生成客户端id
   */
  function generatorClientId(isConnected) {
    var cookieKey = 'zydb';
    let cookie = $.cookie(cookieKey);

    if (cookie && isConnected) {
      $("#onlineimg").attr("src", '/images/online/online.png');
      $("#onlinespan").text("在线[" + cookie + "]");
    } else {
      $("#onlineimg").attr("src", '/images/online/unonline.png');
      $("#onlinespan").text("离线重连");
      var clientCode = cookie;
      if (!clientCode) {
        clientCode = ('000000' + Math.floor(Math.random() * 999999)).slice(-6);
      }

      $.cookie(cookieKey, clientCode, {expires: 30});
      //连接事件
      this.openSocket(clientCode);
    }
  }

  /**
   * 执行命令
   */
  function submitCommand() {
    var command = $("#command").val();
    if (!command) {
      alert("请输入正确的命令行");
      return;
    }

    let debuglog = $("input[name='debuglog']:checked").val();
    if (!debuglog) {
      debuglog = 0;
    }

    var selectPlatform = [];
    $("#platformSelect option:selected").each(function () {
      selectPlatform.push($(this).val());
    });
    if (selectPlatform.length <= 0) {
      alert("请输入平台");
      return;
    }

    var flag = confirm("请确认你输入的信息\n操作命令:" + command);
    if (flag) {
      $.ajax({
        type: "POST",    //请求类型
        url: "/zyDb/exec",
        data: JSON.stringify({"body": {"command": command, "platforms": selectPlatform, "debuglog": debuglog}}),
        contentType: "application/json",
        dataType: "json",
        success: function (res) {
        },
        error: function (msg) {
          alert("执行失败");
        }
      });
    }

  }

  /**
   * 验证是否已经连接状态
   */
  function connected() {
    var cookieKey = 'zydb';
    let clientCode = $.cookie(cookieKey);
    if (!clientCode) {
      generatorClientId(false);
      return;
    }
    $.ajax({
      type: "POST",    //请求类型
      url: "/zyDb/connected",
      data: JSON.stringify({"body": {"clientCode": clientCode}}),
      contentType: "application/json;charset=UTF-8",
      dataType: "json",
      success: function (res) {
        generatorClientId(res.body);
      },
      error: function (msg) {
        alert("建立连接失败");
      }
    });
  }

  /**
   * 清除日志
   */
  function cleanArea() {
    $("#divCenterTextarea").text('');
    $("#divRightTextarea").text('');
    $("#divLeftTextarea").text('');
  }

  /**
   * 初始化平台信息
   */
  function initPlatformInfo() {
    $.ajax({
      type: "POST",    //请求类型
      url: "/zyDb/platform",
      contentType: "application/json;charset=UTF-8",
      dataType: "json",
      success: function (res) {
        $("#platformSelect").empty();//清空
        for (var i = 0; i < res.body.length; i++) {
          $("#platformSelect").append($("<option/>").text(res.body[i]).attr("value", res.body[i])); //动态添加标签
        }
      },
      error: function (msg) {
        alert("获取平台信息失败");
      }
    });
  }

</script>
<body>
<input type="hidden" id="socketUrlId" value='${socketUrl}'/>

<div>
  <!--左边-->
  <div style="max-width: 5%;min-width:5%;float: left;">
    <select multiple="multiple" size="30" id="platformSelect"></select>
  </div>


  <!--右边-->
  <div style="min-width: 95%;max-width: 95%;float: right">
    <!--在线显示状态-->
    <div style="height: auto;">
      <div>
        <button onclick="connected()">点击启动</button>
        <button onclick="cleanArea()">清理日志</button>
      </div>
      <div>
        详细日志:
        <input type="radio" name="debuglog" value="1">是</input>
        <input type="radio" name="debuglog" value="0" checked>否</input>
      </div>
      <div id="classForm">
        <textarea id="command" placeholder="执行命令"
                  style="max-width: 100%;min-width: 100%;max-height: 600px;min-height: 600px;"></textarea>
        <button style="color: red;text-align: center;margin-left: 30%;width: 30%" onclick="submitCommand()"
                type="button">DB执行
        </button>
      </div>
      <span id="onlinespan" style="line-height:60px;position: absolute;right: 100px;top: 30px;">在线</span>
      <img id="onlineimg" onclick="javascript:location.href='/'" src="/images/online/online.png"
           style="line-height:60px; position: absolute;right: 30px;top: 30px;height: 60px;width: 60px;"/>
    </div>

    <div style="float: left;min-width: 96%;max-width: 96%">
      <div id="divLeft">
        <div id="divLeftSpan" style="text-align: center;">操作事件</div>
        <textarea id="divLeftTopTextarea" readonly style="width: 100%;height: 40%;resize:none;color: red"></textarea>
        <textarea id="divLeftTextarea" readonly style="width: 100%;height: 60%;resize:none;"></textarea>
      </div>

      <div id="divRight">
        <div id="divRightSpan" style="text-align: center;">实时日志</div>
        <textarea id="divRightTextarea" readonly style="width: 100%;height: 100%;resize:none;"></textarea>
      </div>

      <div id="divCenter">
        <div id="divCenterSpan" style="text-align: center;">同步日志</div>
        <textarea id="divCenterTextarea" readonly style="height: 100%;width: 40%;resize:none;"></textarea>
      </div>
    </div>
  </div>


</div>


</body>
</html>
<style type="text/css">
  body {
    margin: 0px;
  }

  #divLeft {
    width: 30%;
    height: 600px;
    float: left;
    border: 1px solid black;
  }

  #divCenter {
    width: 100%;
    height: 600px;
    border: 1px solid black;
  }

  #divRight {
    width: 30%;
    height: 600px;
    float: right;
    border: 1px solid black;
  }

</style>

